<template>
<div>
    <j-modal
      width="80%"
      :title="title"
      :visible.sync="editModalVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      @cancel="handleCancleDbSync"
      :destroyOnClose="true"
    >
      <template slot="footer">
        <a-button @click="handleCancleDbSync">
          关闭
        </a-button>
        <a-button type="primary" :loading="syncLoading" @click="handleSure">确定</a-button>
      </template>
      <div class="table-page-search-wrapper warp" :style="{maxHeight:fullscreen?'779px':'588px'}">
        <a-form-model ref="ruleForm" :model="formData" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item label="规则名称" prop="ruleName">
                <a-input v-model="formData.ruleName" placeholder="请输入规则名称"/>
            </a-form-model-item>
            <a-form-model-item label="规则类型" prop="ruleType">
                <a-select placeholder="请选择规则类型" :disabled="formData.id?true:false" v-model="formData.ruleType" :getPopupContainer="node => node.parentNode">
                  <a-select-option v-for="item in ruleList" :key="item.id" :value="item.id">
                    {{ item.typeName }}
                  </a-select-option>
                </a-select>
            </a-form-model-item>
        </a-form-model>
        <div class="handle-btn">
            <a-button icon="plus" @click="AddFieldPartitions">新增字段</a-button>
            <a-button class="delete-btn" type="primary" v-if="fieldSelectedRowKeys.length" icon="minus" @click="removeFields('fieldSelectedRowKeys','ruleFields')">删除</a-button>
        </div>
        <a-table
            size="middle"
            bordered
            :rowKey="(record, index) => index"
            :columns="fieldColumns"
            :data-source="formData.ruleFields"
            :pagination="false"
            :row-selection="{selectedRowKeys: fieldSelectedRowKeys, onChange: onfieldSelectChange}"
            >
            <div slot="fieldName" slot-scope="text, record">
                <a-select show-search v-model="record.fieldName" :getPopupContainer="node => node.parentNode">
                    <a-select-option v-for="field in fieldList" :key="field.id" :value="field.fieldName">
                        {{field.fieldName}}
                    </a-select-option>
                </a-select>
            </div>
            <div slot="ruleFieldTypeCode" slot-scope="text, record">
                <a-select show-search v-model="record.ruleFieldTypeCode" :getPopupContainer="node => node.parentNode">
                    <a-select-option v-for="type in fieldRuleTypeList" :key="type.typeCode" :value="type.typeCode">
                        {{type.typeName}}
                    </a-select-option>
                </a-select>
            </div>
            <div slot="regularExpression" slot-scope="text, record">
                <a-input v-model="record.regularExpression"/>
            </div>
            <div slot="compareMode" slot-scope="text, record">
                <a-input v-model="record.compareMode"/>
            </div>
            <div slot="expectedValue" slot-scope="text, record">
                <a-input v-model="record.expectedValue"/>
            </div>
            <div slot="emptyFlag" slot-scope="text, record">
                <a-checkbox  :checked="record.emptyFlag" @change="checkboxChange(record,'emptyFlag')"></a-checkbox>
            </div>
        </a-table>
      </div>
    </j-modal>
</div>
</template>
<script>
import { getRuleFieldType, addQualityRule, getQualityRuleDetails, editQualityRule, getModelFieldSelectList } from '@/api/api'
const fieldColumns = [
    {
        title: '规则字段',
        width: '12%',
        dataIndex: 'fieldName',
        scopedSlots: { customRender: 'fieldName' }
    },
    {
        title: '规则类别',
        width: '12%',
        dataIndex: 'ruleFieldTypeCode',
        scopedSlots: { customRender: 'ruleFieldTypeCode' }
    },
    {
        title: '校验规则',
        dataIndex: 'regularExpression',
        scopedSlots: { customRender: 'regularExpression' }
    },
    {
        title: '比较方式',
        width: '12%',
        dataIndex: 'compareMode',
        scopedSlots: { customRender: 'compareMode' }
    },
    {
        title: '期望值',
        width: '10%',
        dataIndex: 'expectedValue',
        scopedSlots: { customRender: 'expectedValue' }
    },
    {
        title: '是否判空',
        width: '10%',
        dataIndex: 'emptyFlag',
        scopedSlots: { customRender: 'emptyFlag' }
    },
]
export default {
  name: 'AddRuleModal',
  data() {
    return {
      fieldColumns,
      fieldSelectedRowKeys:[],
      labelCol: { span: 2 },
      wrapperCol: { span: 14 },
      editModalVisible: false,
      title: '编辑',
      syncLoading: false,
      fullscreen: true,
      switchFullscreen: true,
      formData: {
          ruleName:'',
          ruleType:undefined,
          ruleFields:[],
          id:null,
          modelId:null
      },
      fieldList:[],
      fieldRuleTypeList:[],
      ruleList:[
          {id:1,typeName:'私有'},
          {id:2,typeName:'公有'}
      ],
      rules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'change' }
        ],
        ruleType: [
          { required: true, message: '请选择规则类型', trigger: 'change' }
        ]
      },
      newFieldData:{
        fieldName:'',
        ruleFieldTypeCode:'',
        regularExpression:'',
        compareMode:'',
        expectedValue:'',
        emptyFlag:false
      }
    }
  },
  watch: {
    editModalVisible(newVal){
      if(newVal){
        getModelFieldSelectList({modelId:this.formData.modelId}).then((res)=>{
          this.fieldList= res.result || []
        })
      }
    }
  },
  mounted() {
    console.log(this.formData.modelId,'modelId');
    this.getRuleFieldType()
  },
  methods: {
    getRuleFieldType(){
      getRuleFieldType().then(res=>{
        if(res.success){
          this.fieldRuleTypeList = res.result || []
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    removeFields(rowKeysName,modelName) { // 删除数据字段
      var that = this
      this[rowKeysName].sort(function(a, b) { return b - a })
      this[rowKeysName].forEach(function(index) {
        that.formData[modelName].splice(index, 1)
      })
      this[rowKeysName] = []
    },
    AddFieldPartitions() { // 新增分区字段
      const newData = {...this.newFieldData}
      this.formData.ruleFields.push(newData)
    },
    checkboxChange(data, name) {
      if (data[name]) {
        data[name] = false
      } else {
        data[name] = true
      }
    },
    onfieldSelectChange(fieldSelectedRowKeys){
        this.fieldSelectedRowKeys = fieldSelectedRowKeys
    },
    handleCancleDbSync() { // 关闭
      this.formData = this.$options.data().formData
      this.editModalVisible = false
    },
    add() {
      this.editModalVisible = true
    },
    edit() {
      this.editModalVisible = true
      this.getRuleDetail()
    },
    getRuleDetail(){
        console.log(this.formData.id,'id');
        getQualityRuleDetails({id:this.formData.id}).then((res) => {
          if(res.result){
            Object.keys(this.formData).forEach((key)=>{
              this.formData[key] = res.result[key]
            })
          }
        })
    },
    async handleSure() { // 弹窗点击确定
        const valid = await this.$refs['ruleForm'].validate()
        if (valid) {
            this.updateData()
        }
    },
    updateData() { // 保存提交数据
      this.syncLoading = true
      const fun = (res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.handleCancleDbSync()
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
      }
      if (this.formData.id) {
        //编辑质量规则
        editQualityRule(this.formData).then(fun)
        .finally(() => {
          this.syncLoading = false
        })
      } else {
        //新增质量规则
        addQualityRule(this.formData).then(
          fun
        ).finally(() => {
          this.syncLoading = false
        })
      }
    },
  }
}
</script>
<style lang="less" scoped>
.warp .ant-select{
  width: 100%;
}
.table-page-search-wrapper{
  overflow:auto;
}
.handle-btn{
    text-align:right;
    margin-bottom:15px;
    .delete-btn{
        margin-left:15px;
    }
}
</style>
<style scoped>
@import '~@assets/less/common.less'
</style>